<template>
    <Frame
        :steps="steps"
        :current-index="step"
    >
        <FrameContent
            v-if="step === 0"
            :loading="submitLoading"
            :disabled="!canSubmit"
            @on-confirm="handleSubmit"
        >
            <p
                v-if="userType !== 2"
                class="main-title"
            >
                请选择要授权的对象、产品以及产品业务阶段
            </p>
            <p
                v-if="userType == 2"
                class="main-title"
            >
                请选择要授权的主体、对象、产品以及产品业务阶段
            </p>
            <ContentItem
                v-if="userType == 2"
                title="授权主体"
                placeholder="请选择要授权的对象"
                :disabled="companys.length === 1"
                :value="form.company.label"
                @on-click="handlePicker('companys')"
            />
            <ContentItem
                title="授权给"
                placeholder="请选择要授权的对象"
                :value="form.memberInfo.label"
                @on-click="handlePicker('memberInfos')"
            />
            <ContentItem
                title="访问数据的业务"
                placeholder="请选择授权访问数据的业务"
                :value="form.parentScene.label"
                @on-click="handlePicker('parentScenes')"
            />
            <ContentItem
                v-if="childScenes.length > 0"
                title="所办业务阶段"
                placeholder="请选择业务阶段"
                :value="form.childScene.label"
                @on-click="handlePicker('childScenes')"
            />
            <ContentItem
                v-if="userType == 2"
                title="线下签署的数据访问授权协议（可选）"
            >
                <ul class="form-files">
                    <li
                        v-for="(file, index) in files"
                        :key="index"
                    >
                        <Img :src="file.fileBase64" />
                    </li>
                    <li
                        class="add"
                        @click="handleUpload"
                    ></li>
                </ul>
            </ContentItem>
        </FrameContent>
        <FrameContent
            v-if="step === 1"
            btn-text="授权"
            :loading="getPDFLoading"
            :disabled="form2.date === ''"
            @on-confirm="handleAuthorization"
        >
            <p class="main-title">
                请
                <span>授权具体的数据及期限</span>
            </p>

            <ContentItem
                title="授权访问和使用期限至"
                placeholder="请选择日期"
                :value="form2.date"
                @on-click="doPickDate"
            />
            <ContentItem title="授权访问数据及使用方式">
                <dl>
                    <dt>提供原始数据</dt>
                    <dd>
                        {{
                            publicProtocol.length > 0
                                ? publicProtocol[0].fieldNames
                                : '无'
                        }}
                    </dd>
                </dl>
                <dl>
                    <dt>可用不可见（比对、加工计算等）:</dt>
                    <dd>
                        {{
                            privacyProtocol.length > 0
                                ? privacyProtocol[0].fieldNames
                                : '无'
                        }}
                    </dd>
                </dl>
            </ContentItem>
        </FrameContent>
        <FrameContent
            v-if="step === 2"
            btn-text="完成"
            @on-confirm="handlerGoBack"
        >
            <p class="main-title">
                <img
                    class="icon"
                    :src="Icon_tick"
                />
                授权成功
            </p>
            <Img :src="successPDFUrl" />
        </FrameContent>

        <Selector
            ref="selector"
            :data="pickData"
            :title="pickerTitle"
            :selected-data="selectedData"
            :visible.sync="pickerVisible"
            @on-submit="handlePickerConfirm"
        />

        <DatePicker
            v-model="datepickerVisible"
            :current-date="form2.date"
            :min-date="form2.minDate"
            :max-date="maxDate"
            :title="form.childScene.label === '贷后' ? datePickerTip : ''"
            @on-enter="doEnterDate"
        />

        <PdfPopup
            ref="pdfPopup"
            :visible.sync="pdfVisible"
            :src="PDFUrl"
            :loading="getFaceRecognitionLoading"
            :disabled="getFaceRecognitionLoading"
            @on-click="handleSign"
        />
    </Frame>
</template>

<script>
import HeadStep from '@/components/HeadStep';
import ContentItem from './ContentItem';
import PdfPopup from './pdfPopup';
import Selector from './selector';
import { APP_ID, APP_KEY } from '@/config';

import countdown from '@/mixins/countdown.js';
import Icon_tick from '@/assets/images/icon-tick2.png';

import {
    restful_api,
    signContract_api,
    getUrl_api,
    authorize_api,
    getAccessToken_api,
} from '@/api';

export default {
    name: 'Apply',
    components: {
        HeadStep,
        ContentItem,
        PdfPopup,
        Selector,
    },
    mixins: [countdown],
    data() {
        return {
            Icon_tick,
            compTitle: '',
            publicProtocol: null,
            privacyProtocol: null,
            userType: 0, // 是否未公司法人
            companys: [],
            user: {},
            authorization: {},
            childScenes: [],
            accessToken: '',
            srcOrderNo: '',
            // 当前步骤
            step: 0,
            steps: ['授权对象', '确认数据', '完成授权'],

            // STEP0
            form: {
                company: {},
                memberInfo: {},
                parentScene: {},
                childScene: {},
            },
            pickerTitle: '',
            pickerVisible: false,
            pickerType: null,
            // 选择器数据
            pickData: [],
            selectedData: {},
            submitLoading: false,
            files: [],
            // STEP1
            form2: {
                date: '',
                minDate: this.$utils.formatDateTime(new Date().getTime()),
            },
            maxDate: this.$utils.formatDateTime(new Date().getTime()),
            datePickerTip: '授权期限与贷款期限不同可能影响贷款发放',
            datepickerVisible: false,
            pdfVisible: false,
            // PDFUrl: 'https://sirc.shicizhi.com/taap/fileservice/05D38A64C80D11EAA852000C2925F20A/1/1603674589057_743.pdf',
            PDFUrl: '',
            // 短信验证码code
            projectCode: '',
            // 获取 pdf 时
            getPDFLoading: false,
            // 人脸识别状态
            getFaceRecognitionLoading: false,
            // STEP2
            successPDFUrl: '',
        };
    },
    computed: {
        title() {
            let defaultTitle = [null, '个人数据授权', '企业数据授权'];
            return this.compTitle || defaultTitle[this.userType];
        },
        // 能否提交
        canSubmit() {
            let form = this.form;
            let shouldSelectedConpany =
                this.userType == 2 ? this.form.company.label : true;
            let shouldSelectedChildScenes =
                this.childScenes.length > 0 ? form.childScene.label : true;
            return Boolean(
                shouldSelectedConpany &&
                    form.memberInfo.label &&
                    form.parentScene.label &&
                    shouldSelectedChildScenes
            );
        },
    },
    watch: {
        title: {
            immediate: true,
            handler(val) {
                document.title = val;
            },
        },
        pickerVisible(val) {
            !val && (this.compTitle = '');
        },
    },
    mounted() {
        this.main();
    },
    methods: {
        handlerGoBack() {
            this.$router.go(-1);
        },
        // 回到首页
        handleSuccess() {
            let scene =
                JSON.stringify(this.form.childScene) !== '{}'
                    ? this.form.childScene
                    : this.form.parentScene;
            let data = {
                methodId: 'TP350002',
                params: {
                    certCode: this.mztUser.cardNum,
                    certName: this.mztUser.name,
                    phone: this.mztUser.mobile,
                    sceneId: scene.sceneId,
                    expiryDate: this.form2.date.split('-').join(''),
                    verifyType: scene.verifyType,
                    authVisitNum: 9999,
                    accessToken: this.accessToken,
                },
            };
            // 若为企业授权
            if (this.userType === 2) {
                data.params.orgName = this.form.company.orgName;
                data.params.uscc = this.form.company.uscc;
            }
            restful_api(data);
        },
        // 人脸识别(二期修改)
        faceRecognition() {
            let env = process.env.NODE_ENV;
            let params = {
                // 方法名
                methodCode: 'faceCheck',
                // 授权码
                authCode: '2c9bbe698baf4a5d018c855976cc15582c9bbe698baf4a5d',
                // 验证码
                verifyCode: this.srcOrderNo,
                // 发起时间戳
                createTime: Date.parse(new Date()),
                // 0不需要输入用户信息 1需要输入用户信息
                isNeedInputUserInfo: 1,
                // 0不需要认证 1需要认证
                isNeedIdentification: 1,
                // 身份证号码（isNeedIdentification为1时填写）
                cardNumber:
                    this.mztUser.testCardNum && env !== 'govcloud'
                        ? this.mztUser.testCardNum
                        : this.mztUser.cardNum,
                // 用户名（isNeedIdentification为1时填写）
                name:
                    this.mztUser.testName && env !== 'govcloud'
                        ? this.mztUser.testName
                        : this.mztUser.name,
            };
            let that = this;
            that.getFaceRecognitionLoading = true;
            // 旧闽政通人脸识别原生接口
            // app.link.getFaceCheck(async function (result) {
            //     if(result.success === true){
            //         that.handleSignContract()
            //     }
            // })
            // 新闽政通人脸识别原生接口
            app.link.publicMethod(
                async function (result) {
                    if (result.success === true) {
                        that.handleSignContract();
                    }
                },
                function (error) {
                    that.$toast('人脸验证失败，请重试');
                    that.getFaceRecognitionLoading = false;
                    // console.log(error);
                },
                params
            );
        },
        // 协议签署
        async handleSignContract() {
            try {
                let expiredDate = this.form2.date.split('-').join('');
                let data = {
                    fileContentType: this.fileContentType,
                    srcOrderNo: this.srcOrderNo,
                    createContractVO: {
                        expiredDate,
                        templateId: this.templateId,
                        signInfos: [
                            {
                                userId: this.user.userId,
                                authorizationTime: this.$utils.formatDateTime(
                                    new Date(),
                                    'yyyyMMddhhmmss'
                                ),
                                location: window.location.origin,
                                signLocation: 'Signature1',
                                projectCode: this.projectCode,
                                isProxySign: 1,
                            },
                        ],
                        textValueInfo: {
                            IDCard: this.mztUser.cardNum,
                            user: this.mztUser.name,
                            expiredDate:
                                expiredDate.substring(0, 4) +
                                '年' +
                                expiredDate.substring(4, 6) +
                                '月' +
                                expiredDate.substring(6, 8) +
                                '日',
                        },
                    },
                };
                if (this.userType === 2) {
                    data.createContractVO.textValueInfo.companyName =
                        this.form.company.label;
                }
                let res = await signContract_api(data, {
                    accessToken: this.accessToken,
                });
                if (res) {
                    const { fileBase64 } = res;
                    this.getFaceRecognitionLoading = false;
                    this.pdfVisible = false;
                    this.step++;
                    this.successPDFUrl = fileBase64;
                    this.handleSuccess();
                }
            } catch (e) {
                this.getFaceRecognitionLoading = false;
                this.$toast(e);
            }
        },
        // 签署
        async handleSign() {
            // 二期直接走人脸识别验证
            this.faceRecognition();
        },
        // 查看授权书
        async handleAuthorization() {
            try {
                if (this.form2.date === '') return;
                // 获取 pdf 中
                this.getPDFLoading = true;

                let sceneId =
                    this.form.childScene.sceneId || this.form.parentScene.sceneId;

                let data = await getUrl_api(
                    `/taap/fileservice/${this.userType}/protocol.json`
                );
                let { fileContentType, fileName, templateId } = data[0];
                this.fileContentType = fileContentType;
                this.templateId = templateId;

                let params = {
                    methodId: 'TP350007',
                    params: {
                        srcOrderNo: this.srcOrderNo, // 业务流水号
                        sceneId: sceneId, // 产品标识
                        userType: this.userType, // 用户类型，1：个人 2：机构
                        expiryDate: this.$utils.formatDateTime(
                            this.form2.date,
                            'yyyy年MM月dd日'
                        ), // 截止有效期
                        fileName: fileName, // 文件名
                        certName: this.mztUser.name, // 授权人姓名
                        certCode: this.mztUser.cardNum, // 授权人姓名
                    },
                };
                if (this.form.company?.orgName || this.form.company?.uscc) {
                    params.params.orgName = this.form.company.orgName; // 授权单位名称
                    params.params.uscc = this.form.company.uscc; // 授权单位统一信用代码
                }
                let { fileStream } = await restful_api(params);
                this.PDFUrl = fileStream;

                this.getPDFLoading = false;
                this.pdfVisible = true;
            } catch (e) {
                this.getPDFLoading = false;
                this.$toast(e);
            }
        },
        handleUpload() {
            try {
                let that = this;
                if (app) {
                    app.link.getTakePictures(
                        function (res) {
                            let tmp = [];
                            res.images.forEach((item, index) => {
                                tmp.push({
                                    fileName: res.names[index],
                                    fileBase64: item,
                                });
                            });
                            if (res.images && res.images.length > 0) {
                                that.files = [...that.files, ...tmp];
                            }
                        },
                        {
                            pictureNum: 9,
                        }
                    );
                }
            } catch (e) {}
        },
        // 选择授权日期
        doEnterDate(date) {
            this.form2.date = this.$utils.formatDateTime(date, 'yyyy-MM-dd');
        },
        // 授权日期选择插件
        doPickDate() {
            this.datepickerVisible = true;
        },
        // 获取协议信息
        async getProtocolDoc(srcOrderNo) {
            let data = {
                methodId: 'TP350014',
                params: { srcOrderNo },
            };
            let { sceneFields } = await restful_api(data);
            this.publicProtocol = sceneFields.filter((item) => item.levelRule === '0');
            this.privacyProtocol = sceneFields.filter((item) => item.levelRule !== '0');
        },
        // 获取用户信息
        async getUserId(accessToken) {
            try {
                this.accessToken = accessToken;
                this.user = await authorize_api(
                    {
                        authenticationMode: '公安部',
                    },
                    { accessToken }
                );
            } catch (e) {
                this.$toast(e);
            }
        },
        // 获取空协议Url
        async getProtocol(sceneId) {
            // let { data } = await getUrl_api(`/taap/fileservice/${sceneId}/${this.userType}/protocol.json`)
            // let { fileContentType, fileName, templateId } = data[0]
            // this.fileContentType = fileContentType
            // this.templateId = templateId
            // this.PDFUrl = `/taap/fileservice/${sceneId}/${this.userType}/${fileName}`
            // this.PDFUrl = `http://193.100.100.99:8090/taap/fileservice/05d38a64c80d11eaa852000c2925f20a/1/1603674589057_743.pdf`
        },
        // 提交表单信息
        async handleSubmit() {
            try {
                let sceneId =
                    this.form.childScene.sceneId || this.form.parentScene.sceneId;
                let data = {
                    appId: APP_ID,
                    appKey: APP_KEY,
                    certCode: this.mztUser.cardNum,
                    certName: this.mztUser.name,
                    phone: this.mztUser.mobile,
                    extInfo: {
                        sceneId,
                        appTar: this.form.memberInfo.accessKeyId,
                    },
                };
                // 若为企业授权
                if (this.userType === 2) {
                    data.orgName = this.form.company.orgName;
                    data.uscc = this.form.company.uscc;
                    data.fileList = this.files;
                }
                this.submitLoading = true;
                let { accessToken, srcOrderNo } = await getAccessToken_api(data);
                this.srcOrderNo = srcOrderNo;
                await this.getUserId(accessToken);
                await this.getProtocolDoc(srcOrderNo);
                // 默认授权日期为最大天数
                this.form2.date = this.maxDate;
                this.step++;
                this.submitLoading = false;
            } catch (e) {
                this.submitLoading = false;
                this.$toast(e);
            }
        },
        // 选择选项
        handlePickerConfirm(res) {
            let type = this.pickerType.substring(0, this.pickerType.length - 1);
            switch (this.pickerType) {
                case 'memberInfos':
                    if (this.form[type].label !== res.label) {
                        this.form.parentScene = {};
                        this.form.childScene = {};
                    }
                    break;
                case 'parentScenes':
                    if (this.form[type].label !== res.label) {
                        this.form.childScene = {};
                        this.childScenes = this.authorization['childScenes'].filter(
                            (item) => item.parentId === res.sceneId
                        );
                    }
                    this.maxDate = this.$utils.formatDateTime(
                        new Date().getTime() + res.authMaxDate * 24 * 60 * 60 * 1000,
                        'yyyy-MM-dd'
                    );
                    break;
                case 'childScenes':
                    this.maxDate = this.$utils.formatDateTime(
                        new Date().getTime() + res.authMaxDate * 24 * 60 * 60 * 1000,
                        'yyyy-MM-dd'
                    );
                    break;
            }
            this.form[type] = res;
            this.pickerType = null;
        },
        // 弹出选择器
        handlePicker(type) {
            let title = '';
            let pickData = [];
            let noDataTip = '';
            switch (type) {
                case 'companys':
                    noDataTip = '暂无可授权主体';
                    pickData = this.companys;
                    title = `您担任法人代表的企业有以下${this.companys.length}家`;
                    if (!Array.isArray(pickData)) return;
                    this.compTitle = '选择授权主体';
                    break;
                case 'memberInfos':
                    noDataTip = '暂无可授权对象';
                    pickData = this.authorization && this.authorization[type];
                    if (!Array.isArray(pickData)) return;
                    this.compTitle = '选择授权对象';
                    break;
                case 'parentScenes':
                    noDataTip = '暂无可选择业务';
                    if (!this.form.memberInfo.label) return this.$toast('请选择授权对象');
                    pickData = this.authorization[type].map(
                        (item) => item.memberId === this.form.memberInfo.memberId && item
                    );
                    this.compTitle = '选择业务';
                    break;
                case 'childScenes':
                    noDataTip = '暂无可选择业务阶段';
                    if (!this.form.memberInfo.label) return this.$toast('请选择授权对象');
                    if (!this.form.parentScene.label) {
                        return this.$toast('请选择授权访问数据的产品');
                    }
            }
            if (pickData.length === 0) {
                this.$toast(noDataTip);
            } else {
                this.selectedData = this.form[type.substring(0, type.length - 1)];
                this.pickerType = type;
                this.pickerTitle = title;
                this.pickData = pickData;
                this.pickerVisible = true;
            }
        },
        // 获取数据
        async getData() {
            let data = {
                methodId: 'TP350001',
                params: {
                    appId: APP_ID,
                    appKey: APP_KEY,
                    mainType: String(this.userType),
                },
            };
            let res = await restful_api(data);
            this.authorization.memberInfos =
                res.memberInfos &&
                res.memberInfos.map(
                    (item) => (item.label = item.cnnameShort || item.cnname) && item
                );
            this.authorization.parentScenes =
                res.parentScenes &&
                res.parentScenes.map((item) => (item.label = item.sceneName) && item);
            this.authorization.childScenes =
                res.childScenes &&
                res.childScenes.map((item) => (item.label = item.sceneName));
        },
        // 获取旗下公司
        async getCompanyData() {
            let data = {
                methodId: 'TP350003',
                params: {
                    certCode: this.mztUser.cardNum,
                },
            };
            // 根据身份证号码查询名下企业
            let res = await restful_api(data);
            return res.list.map((item) => (item.label = item.orgName) && item);
        },
        async main() {
            this.userType = Number(this.$route.query.userType);
            // 若为法人用户则获取公司数据
            if (this.userType === 2) {
                this.companys = await this.getCompanyData();
                this.form.company = this.companys[0];
            }
            this.getData();
        },
        // 路由跳转
        handleTo(nav) {
            this.$router.push({ path: nav });
        },
    },
};
</script>
<style lang="less" scoped>
@import './form.less';
</style>

<style scoped>
dl {
    font-size: 15px;
    line-height: 30px;
}
dt {
    color: #333;
    font-weight: 600;
}
dd {
    color: #666;
    word-wrap: break-word;
    word-break: normal;
}

.form-files li /deep/ .img-wrapper {
    display: flex;
    align-self: center;
    justify-content: center;
    overflow: hidden;
}

.form-files li /deep/ img {
    width: 100%;
    object-fit: cover;
    object-position: center;
}

.wrapper {
    background: url('../../assets/images/banner.png') no-repeat;
    background-size: 100% auto;
}
.title {
    font-size: 16px;
    line-height: 48px;
    font-weight: 600;
    text-align: center;
}
.title span {
    position: relative;
}
.title span::before,
.title span::after {
    position: absolute;
    top: 50%;
    display: block;
    width: 56px;
    height: 1px;
    content: '';
}
.title span::before {
    right: calc(100% + 6px);
    background-image: linear-gradient(
        270deg,
        rgb(1, 144, 255) 0%,
        rgba(1, 144, 255, 0) 100%
    );
}
.title span::after {
    left: calc(100% + 6px);
    background-image: linear-gradient(
        90deg,
        rgb(1, 144, 255) 0%,
        rgba(1, 144, 255, 0) 100%
    );
}
.font_size-14 {
    font-size: 14px;
}
.font_size-16 {
    font-size: 16px;
}
.col-999 {
    color: #999;
}
.margin_bottom-5 {
    margin-bottom: 5px;
}

.wrapper {
    position: fixed;
    top: 0;
    bottom: 0;
    display: flex;
    flex-direction: column;
    background-color: #fefefe;
}
.header {
    width: 100%;
    padding-top: 18px;
    margin-bottom: 20px;
    text-align: center;
    color: #fff;
}
.header .header-score {
    margin-bottom: 6px;
    font-size: 50px;
    line-height: 50px;
}
.header .header-title {
    padding-top: 20px;
    margin-bottom: 10px;
    font-size: 24px;
    line-height: 24px;
    letter-spacing: 1px;
    text-shadow: 2px 2px 2px #005bbc99;
}
.header .header-subtitle {
    padding-top: 20px;
    font-size: 18px;
    text-shadow: -2px -2px 2px #005bbc99;
    line-height: 26px;
    letter-spacing: 2px;
}
.header .header-des {
    font-size: 12px;
}
.content-wrapper {
    position: fixed;
    top: 124px;
    bottom: 0;
    width: 100vw;
    overflow-y: scroll;
}
.head-step {
    margin: 0 16px;
}
.content {
    display: flex;
    flex-direction: column;
    padding-bottom: 60px;
    margin: 0 16px;
    min-height: 100%;
}
.content > li {
    min-height: 100%;
    padding: 20px 28px;
    border-radius: 6px;
    margin-bottom: 10px;
    background-color: #fff;
    box-shadow: 0px 2px 15px 5px #00000012;
    overflow: hidden;
}
.content > li:last-child {
    margin-bottom: 0px;
    border-bottom-right-radius: 0px;
    border-bottom-left-radius: 0px;
}
.content > li.full {
    flex: 1;
}

.content .main-title {
    justify-content: center;
    border-bottom: solid thin #efefef;
    margin-top: -20px;
    margin-bottom: 20px;
    font-size: 16px;
    line-height: 50px;
    text-align: center;
    font-weight: 700;
}

.content .main-title .icon {
    width: 16px;
    margin-right: 8px;
}

.content .main-title span {
    color: #237ef2;
}

.content .pdf-wrapper {
    width: 100vw;
    margin: 0 -44px;
}
.content.step3 li > p:not([class]) span:first-child {
    color: #999;
}
.content .status {
    display: block;
    width: 24px;
    height: 24px;
    border-radius: 50%;
    font-size: 12px;
    line-height: 24px;
    text-align: center;
    color: #fff;
}
.content .status.success {
    background-color: #5bd298;
}
.content .status.error {
    background-color: #ee4933;
}
.content .line {
    flex: 1;
    height: 0;
    border-top: solid thin #eaeaea;
    margin: 0 10px;
}
.loading-wrapper {
    position: relative;
    width: 82px;
    height: 82px;
    border: solid 3px #64a7ff;
    border-radius: 50%;
    margin: 150px auto 30px;
}
.loading-wrapper + p {
    font-size: 12px;
    color: #0190ff;
    justify-content: center;
}
.loading {
    position: relative;
    display: flex;
    height: 100%;
    flex-direction: column;
    align-items: center;
    padding-top: 11px;
}
.loading > div {
    display: flex;
}
.loading > div > * {
    margin: -1px 2px;
}
.quota-title {
    font-size: 12px;
    line-height: 36px;
    color: #0190ff;
}
.quota-warpper {
    display: flex;
    justify-content: center;
    text-align: center;
    font-size: 24px;
    line-height: 72px;
    color: #a9d9ff;
}
.quota-warpper > div {
    margin: 0 10px;
}
.quota {
    font-size: 36px;
    color: #1ac184;
}
</style>
